package com.voja.mrvica2.db;

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;

/**
 * SQLite Database Class
 * @author Voislav Jovanovic
 *
 */
public class DB {
    
    SQLiteHelper helper;
    Context      context;
    Cursor       cursor;
    
    public DB(Context c) {
        context = c;
        helper = new SQLiteHelper(context, createDatabase());
    }
    
    /**
     * Execute SQL and return result Cursor
     * @param  String sql
     * @return Cursor
     */
    public Cursor query(String sql) {
        return helper.query(sql);
    }
    
    /**
     * Execute SQL and return number of affected rows
     * @param  String sql
     * @return int
     */
    public int execute(String sql) {
        return helper.execute(sql);
    }
    
    /**
     * Generate DB CREATE statements
     * @return ArrayList<String>
     */
    private ArrayList<String> createDatabase() {
        ArrayList<String> sqls = new ArrayList<String>();
        
        // Continents
        sqls.add( "CREATE TABLE continents (" +
                  "id    INTEGER PRIMARY KEY AUTOINCREMENT," +
                  "name  VARCHAR(255) NOT NULL," +
                  "image VARCHAR(255)" +
                  ");" );
        
        // Countries
        sqls.add( "CREATE TABLE countries (" +
                  "id           INTEGER PRIMARY KEY AUTOINCREMENT," +
                  "continent_id INTEGER NOT NULL," +
                  "name         VARCHAR(255) NOT NULL," +
                  "image        VARCHAR(255)," +
                  "link         VARCHAR(255)," +
                  "description  TEXT" +
                  ");" );
        
        // Sync
        sqls.add( "CREATE TABLE sync (" +
                  "key   VARCHAR(20) NOT NULL," +
                  "stamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP" +
                  ");" );
        sqls.add( "INSERT INTO sync(key, stamp) VALUES('continents', 0);" );
        
        return sqls;
    }
    
    public String prepForSave(String txt) {
        txt = txt.replaceAll("'", "\\'");
        return txt;
    }
}
